/**
 * @author SongJun
 * @description 两数相加
 * @date 2021/9/10 10:14
 */
public class AddTwoNumbers {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static void main(String[] args) {
        ListNode a = new ListNode(9);
        a.next = new ListNode(9);
        a.next.next = new ListNode(9);

        ListNode b = new ListNode(9);

        AddTwoNumbers instance = new AddTwoNumbers();
        ListNode listNode = instance.addTwoNumbers(a, b);
        String s = "";
        while(true){
            s = listNode.val+s;
            if(listNode.next == null){
                System.out.println(s);
                return;
            }
            listNode = listNode.next;
        }

    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ret = null;
        ListNode cur = ret;
        ListNode left = l1;
        ListNode right = l2;
        int up = 0;
        while (true){
            int l = left == null ? 0 : left.val;
            int r = right == null ? 0 :right.val;
            if(left == null && right == null){
                if(up != 0){
                    cur.next = new ListNode(up);
                }
                return ret;
            }
            int sum = l + r + up;
            int effect = sum % 10;
            up = sum == effect ? 0 : 1;
            if(ret == null){
                ret = new ListNode(effect);
                cur = ret;
            } else {
                cur.next = new ListNode(effect);
                cur = cur.next;
            }
            left = left == null ? null : left.next;
            right = right == null ? null : right.next;
        }
    }
}
